package com.gfl.trivialrestclient.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.gfl.trivialrestclient.controllers.forms.AjaxSubmitionStatus;

/**
 * Ajax auth failure handler. Ajax detection is based on
 * X-Requested-With:XMLHttpRequest HTTP header.
 * 
 * @author Bedlam
 * 
 */
public class AjaxAuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {

		// detect ajax request
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			String redirectUrl = request.getContextPath()
					+ super.getDefaultTargetUrl();

			response.setContentType("application/json; charset=UTF-8");

			AjaxSubmitionStatus successStatus = new AjaxSubmitionStatus(true);
			successStatus.setTargetUrl(redirectUrl);

			response.getWriter().print(
					new ObjectMapper().writeValueAsString(successStatus));

			response.getWriter().flush();
		} else {
			// traditional html success
			super.onAuthenticationSuccess(request, response, authentication);
		}

	}

}
